import React, { Component, createRef } from 'react'
import {
  Breadcrumb,
  Button,
  Divider,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Upload,
} from 'antd'
import 'react-quill/dist/quill.snow.css'
import { addArticleApi, getArticleDetailApi } from 'api/article'
import Channel from 'components/Channel'
import ReactQuill from 'react-quill'
import styles from './index.module.scss'

export default class Publish extends Component {
  state = {
    type: 1,
    fileList: [],
    isModalVisible: false,
    previewImageUrl: '',
  }
  formRef = createRef()

  //发表或存为草稿
  onSave = async (value, draft = false) => {
    const id = this.props.match.params.id
    // 对封面照片数量的校验
    if (value.type !== this.state.fileList.length && value.type !== -1) {
      return message.warning('上传对应数量的封面图')
    }
    // 发送请求所需要的数据
    const params = {
      ...value,
      cover: {
        type: value.type === -1 ? 0 : value.type,
        images: this.state.fileList.map((item) => item.response?.data?.url),
      },
      draft,
    }
    if (id) {
      // message.success('修改文章成功')
      params.target = id
      console.log('保存修改', params)
    } else {
      // console.log('点击提交', value)  ==>   提到全局了
      // console.log(params)  ==>   提到全局了
      await addArticleApi(params)
    }
  }

  // 提交表单
  onFinish = async (value) => {
    await this.onSave(value)
    message.success('文章添加成功')
    this.props.history.push('/home/article')
  }

  // 上传图片变化
  uploadChange = ({ file, fileList }) => {
    // console.log('传图', fileList)
    this.setState({ fileList })
  }

  // 上传图片数量
  onRadioChange = (e) => {
    const { value } = e.target
    this.setState({
      type: value,
      fileList: value !== 3 ? [] : this.state.fileList,
    })
  }

  // 上传图片弹窗
  onUploadPreview = (file) => {
    console.log('图片', file)
    this.setState({
      isModalVisible: true,
      previewImageUrl: file.url || file.response.data.url,
      // previewImageUrl: file.url,
    })
  }

  // 上传图片校验格式
  onBeforeUpload = (file) => {
    console.log('123')
    const imageType = ['image/jpeg', 'image/png']
    if (!imageType.includes(file.type)) {
      message.warning('图片上传格式错误')
      return false
    }
    return true
  }

  // 存为草稿
  onAddDraft = async () => {
    const value = await this.formRef.current.validateFields()
    // console.log('存为草稿')
    await this.onSave(value, true)
    message.success('存为草稿成功')
    this.props.history.push('/home/article')
  }

  // 获取文章详情
  getArticleDetail = async () => {
    const id = this.props.match.params.id
    if (!id) return
    const res = await getArticleDetailApi(id)
    console.log('获取文章详情', res)
    this.formRef.current.setFieldsValue({ ...res, type: res.cover.type || -1 })
    this.setState({
      fileList: res.cover.images.map((item) => {
        return { url: item }
      }),
    })
  }

  componentDidMount() {
    this.getArticleDetail()
    // console.log('进', this.props.match.params.id)
  }

  render() {
    const { type, fileList, isModalVisible, previewImageUrl } = this.state
    return (
      <div className={styles.publish}>
        {/* 面包屑 */}
        <Breadcrumb>
          <Breadcrumb.Item onClick={() => this.props.history.push('/home')}>
            首页
          </Breadcrumb.Item>
          <Breadcrumb.Item>发布文章</Breadcrumb.Item>
        </Breadcrumb>
        <Divider />

        {/* 表单区域 */}
        <Form
          wrapperCol={{ span: 11 }}
          labelCol={{ span: 5 }}
          onFinish={this.onFinish}
          name="publishForm"
          autoComplete="off"
          initialValues={{ type: this.state.type }}
          ref={this.formRef}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择频道' }]}
          >
            <Channel />
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group onChange={this.onRadioChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={-1}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {/* 上传 */}
          <Form.Item wrapperCol={{ offset: 5 }}>
            <Upload
              name="image"
              listType="picture-card"
              className="avatar-uploader"
              action="http://geek.itheima.net/v1_0/upload"
              maxCount={type}
              fileList={fileList}
              onChange={this.uploadChange}
              onPreview={this.onUploadPreview}
              beforeUpload={this.onUploadBeforeUpload}
              accept=".jpg,.png"
            >
              上传
            </Upload>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请填写文章内容' }]}
          >
            <ReactQuill placeholder="请输入文章内容..." />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button type="primary" htmlType="submit" style={{ marginLeft: 45 }}>
              {this.props.match.params.id ? '修改' : '发布'}文章
            </Button>
            <Button
              onClick={this.onAddDraft}
              type="ghost"
              style={{ marginLeft: 15 }}
            >
              存为草稿
            </Button>
          </Form.Item>
        </Form>

        {/* 图片预览弹出框 */}
        <Modal
          onCancel={() => {
            this.setState({ isModalVisible: false })
          }}
          footer={null}
          visible={isModalVisible}
        >
          <img style={{ width: '100%', padding: 10 }} src={previewImageUrl} />
        </Modal>
      </div>
    )
  }
}
